import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from "@/stores/user";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // {
    //   path: '/yindao',
    //   name: 'yindao',
    //   component: () => import('../views/yindao/index.vue')
    // },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login/index.vue')
    },
    {
      path: '/regist',
      name: 'regist',
      component: () => import('../views/regist/index.vue')
    },
    {
      path: '/',
      name: 'home',
      component: () => import('../views/home/index.vue')
    },
    {
      path: '/mine',
      name: 'mine',
      component: () => import('../views/mine/index.vue')
    },
    {
      path: '/modifyPassword',
      name: 'modifyPassword',
      component: () => import('../views/mine/conponents/ModifyPassword.vue')
    },
    {
      path: '/article/:id',
      name: 'ArticleContent',
      component: () => import('../views/home/components/articleContent.vue')
    },
  ]
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();

  // 判断是否需要登录权限
  if (to.meta.requiresAuth) {
    // 检查是否有 token
    if (!userStore.token) {
      // 没有 token，跳转到登录页
      next('/login');
    } else {
      // 有 token，允许访问
      next();
    }
  } else {
    next();
  }
});

export default router
